package com.owulia.leetcode.num.linked.list;

public class Reversal {

    public static ListNode reverseList(ListNode head) {
        if (null == head || null == head.next) {
            return head;
        }
        int count = 0;
        ListNode newHead = head;
        while (null != newHead.next) {
            newHead = newHead.next;
            count++;
        }
        newHead.next = head;
        ListNode preHead = newHead;
        for (int i = count - 1; i >= 0; i--) {
            ListNode nowTail = head;
            for (int j = 0; j < i; j++) {
                nowTail = nowTail.next;
            }
            nowTail.next = preHead.next;
            preHead.next = nowTail;
            preHead = nowTail;
        }
        head.next = null;
        return newHead;
    }


    public static ListNode reverseList1(ListNode head) {
        if (null == head || null == head.next) {
            return head;
        }
        ListNode prev = null;
        ListNode current = head;
        while (current != null) {
            ListNode next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        return prev;
    }





    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);

        ListNode newHead = reverseList1(head);
        do {
            System.out.printf("\t" + newHead.val);
            newHead = newHead.next;
        } while (null != newHead.next);
        System.out.printf("\t" + newHead.val);
    }
}
